package de.crm.storage;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;

import de.crm.storage.impl.CustomerImpl;

public class StorageFacade {

	public static Customer createCustomer() {
		return new CustomerImpl();
	}

	public static List<IPersistentObject> read() {
		List<IPersistentObject> persistenceObjectList = new ArrayList<IPersistentObject>();
		
		try {
			BufferedReader bufferedReader = new BufferedReader(new FileReader(new File("E:/ausgabe.csv")));
			
			String line = null;
			
			while((line = bufferedReader.readLine()) != null) {
				List<String> fieldList = new ArrayList<String>();
				StringTokenizer tokenizer = new StringTokenizer(line,";", true);
				
				while(tokenizer.hasMoreTokens()) {
					String token = tokenizer.nextToken();
					
					if( !token.equals(";")) {
						fieldList.add(token);
					} else {
						fieldList.add("");
					}
				}
				
				Customer customer = StorageFacade.createCustomer();
				
				customer.setFields(fieldList);
				
				persistenceObjectList.add(customer);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return persistenceObjectList;
	}

	public static void store (IPersistentObject object) {
		BufferedWriter bufferedWriter;
		try {
			bufferedWriter = new BufferedWriter(new FileWriter(new File ("E:/ausgabe.csv"), true));
			String ausgabe = "";

			Iterator<String> iterator = object.fieldIterator();

			while(iterator.hasNext()) {
				String nextToken = iterator.next();
				
				if(nextToken != null && !nextToken.equals("null")) {
					ausgabe += nextToken;
				}

				if(iterator.hasNext()) {
					ausgabe += ";";
				}
								
			}

			bufferedWriter.append(ausgabe);
			bufferedWriter.append("\n");
			bufferedWriter.flush();
			bufferedWriter.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
